package message

import (
	"awesomeProject/userop-web/api"
	"awesomeProject/userop-web/forms"
	"awesomeProject/userop-web/global"
	"awesomeProject/userop-web/models"
	"awesomeProject/userop-web/proto"
	"context"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
)

func List(ctx *gin.Context) {

	userId, _ := ctx.Get("userId")

	var request proto.MessageRequest

	claims, _ := ctx.Get("claims")
	model := claims.(*models.CustomClaims)
	if model.AuthorityId == 1 {
		request.UserId = int32(userId.(uint))
	}

	rsp, err := global.MessageClient.MessageList(context.Background(), &request)
	if err != nil {
		zap.S().Error("获取用户留言列表失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	rspMap := make(map[string]interface{})
	rspMap["total"] = rsp.Total

	messageList := make([]interface{}, 0)
	for _, data := range rsp.Data {
		message := make(map[string]interface{})
		message["id"] = data.Id
		message["user_id"] = data.UserId
		message["message"] = data.Message
		message["type"] = data.MessageType
		message["subject"] = data.Subject
		message["file"] = data.File

		messageList = append(messageList, message)
	}

	rspMap["data"] = messageList
	ctx.JSON(http.StatusOK, rspMap)
}

func New(ctx *gin.Context) {

	userId, _ := ctx.Get("userId")

	messageForm := forms.MessageForm{}
	if err := ctx.ShouldBind(&messageForm); err != nil {
		zap.S().Info("解析表单失败")
		api.HandleValidateError(err, ctx)
		return
	}

	var request proto.MessageRequest
	request.UserId = int32(userId.(uint))
	request.Message = messageForm.Message
	request.MessageType = messageForm.MessageType
	request.Subject = messageForm.Subject
	request.File = messageForm.File

	rsp, err := global.MessageClient.CreateMessage(context.Background(), &request)
	if err != nil {
		zap.S().Info("添加留言失败")
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"id": rsp.Id,
	})

}
